/**
* TG_Coder: Dzlua
* Email: 505544956@qq.com
* Time: 2017/05/10
*/
#include "Parser.h"
#include "TGPath.h"
#include <iostream>
using namespace std;

//not show console
//#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"")

void show() {
    cout << "--------------------------------" << endl;
    cout << "Welcome to use ts2new to translate old tango accounts2.dat to addalt.dat!" << endl;
    cout << "       Copyright 2017 Dzlua.All right reserved." << endl;
    cout << "    Usage: ts2new [infile/-s/--search] [outfile]" << endl;
    cout << "        -s/--search:  a cmd. auto search accounts2.dat in tango data path. as default." << endl;
    cout << "        infile:  the file name to translate. default: accounts2.dat" << endl;
    cout << "        outfile:  the file name to save. default: addalt.dat" << endl;
    cout << "    Sample:" << endl;
    cout << "        ts2new" << endl;
    cout << "        ts2new accounts2.dat" << endl;
    cout << "        ts2new accounts2.dat addalt.dat" << endl;
    cout << "        ts2new --search" << endl;
    cout << "        ts2new -s addalt.dat" << endl;
    cout << endl;
}

int main(int argc, char** argv)
{
    bool bShowCmd = true;
    bool help = false;
    std::string file;
    std::string dst = "addalt.dat";
    if (argc > 1)
        file = argv[1];
    if (argc > 2)
        dst = argv[2];
    if (file == "-h" || file == "--help")
        help = true;

    if (file.empty() || file == "-s" || file == "-search") {
        file = TGPath::GetAccoutsFile();
        if (file.empty()) {
            std::cout << "failed! no accounts." << std::endl;
            return false;
        }
        
    }

    if (file == "-tgtrans") {
        file = TGPath::GetAccoutsFile();
        bShowCmd = false;
    }

    if (bShowCmd) {
        /*AllocConsole();
        freopen("CONOUT$","w+t",stdout);
        freopen("CONIN$","r+t",stdin);
        freopen("CONOUT$","w+t",stderr);*/
    } else {
        ::FreeConsole();
    }

    show();

    if (help)
        return 0;
    
    cout << "-> ts2new " << file << " " << dst << endl;

    parser::VData* vdata = parser::ParserDataFile(file);
    if (vdata && vdata->size() > 0) {
        // old data file
        if ( !parser::WriteData2File(dst, vdata) ) {
            std::cout << "failed!" << std::endl;
            return 0;
        } 
    } else {
        // new data file
        if ( !parser::WriteData2File(dst, file) ) {
            std::cout << "failed!" << std::endl;
            return 0;
        } 
    }

    std::cout << "done!" << std::endl;
    return 0;
}